package com.example.chattingroom.api;

import com.example.chattingroom.model.User;
import com.example.chattingroom.model.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserAPI {
    @Resource
    UserMapper userMapper;

    //登录
    @RequestMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req)
    {
        //先用Mapper去数据库查看对应的用户名，能找到对应用户再进行密码匹配
        User user = userMapper.selectByName(username);
        if( user == null || !user.getPassword().equals(password))
        {
            System.out.println("登录失败！用户名或者密码错误！"+user);
            return new User();
        }

        //匹配成功就登陆，创建会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);


        //不应该把password暴露出来，设置password为空
        user.setPassword("");
        return user;
    }

    //注册
    @RequestMapping("/register")
    @ResponseBody
    public Object register(String username,String password)
    {
        //创建一个对象
        User user = null;
        try {
            //给数据库插入记录（用户对应的数据）
            //初始化user对象，再做插入数据操作
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            //用户名是unique key，不可重复
            int ret = userMapper.insert(user);
            System.out.println("注册："+ret);
        } catch (DuplicateKeyException e) {
            //当注册用户的名字重复就会抛异常，注册失败
            user = new User();
            System.out.println("注册失败！username:"+username+"重复注册！");
        }
        return user;
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req){
        //1.先从请求中获取到会话
        HttpSession session = req.getSession(false);
        if(session == null)
        {
            //会话不存在，用户没有登录，返回一个空的对象
            System.out.println("[getUserInfo]当前获取不到session对象！");
            return new User();
        }
        //2.从会话中获取之前保存的用户对象
        User user = (User)session.getAttribute("user");

        if(user==null){
            System.out.println("[getUserInfo]当前获取不到user对象!" );
        }
        user.setPassword("");
        return user;
    }
}
